package com.dragee.utils.weiXin;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dragee.common.P;
import com.dragee.config.exception.BusinessException;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/** 微信
 * @author tys on 2023/5/24
 */
public class WeiXinUtil {
    private static final String appId = "wx9a0a0b0df5095ab4";
    private static final String secret = "f561db13589a39c9c6bbe56e9f4270eb";
    private static final String openIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";





    public static OpenIdAndSessionKey getOpenId(String code) {
        OpenIdAndSessionKey openIdAndSessionKey =new OpenIdAndSessionKey();
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            String requestUrl = String.format(openIdUrl, appId, secret, code);
            HttpGet httpGet = new HttpGet(requestUrl);
            HttpEntity responseEntity = httpClient.execute(httpGet).getEntity();
            if (responseEntity != null) {
                String responseStr = EntityUtils.toString(responseEntity);
                if (responseStr.contains("openid")) {
                    P.green(responseStr);
                    JSONObject wxResponse = new JSONObject(responseStr);
                    openIdAndSessionKey.setOpenId((String) wxResponse.get("openid"));
                    openIdAndSessionKey.setSessionKey((String) wxResponse.get("session_key"));
                    return openIdAndSessionKey;
                } else {
                    P.red(responseStr);
                }
            }
        }catch (IOException e) {
            P.red(e.getMessage());
        }
        return null;
    }


    /**
     * 获取微信accesstoken
     * @return
     */
    public static String getWxAcesstoken() {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        try {
            String jsonstr = HttpUtil.get(tokenUrl);
            JSONObject jsonObject  = JSONUtil.parseObj(jsonstr);
            if (jsonObject.containsKey("access_token")) {
                String accesstoken = jsonObject.get("access_token").toString();
                return accesstoken;
            } else {
                throw new BusinessException("未获取到token");
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 获取微信手机号
     * @return
     */
    public static String getUserPhoneNumber(String code) {
        @Data
        class Result {
            private Integer errcode;
            private String errmsg;
            private ResultNumber phone_info;
            @Data
            class ResultNumber {
                private String purePhoneNumber;
                private String phoneNumber;
            }
        }

        String tokenUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+getWxAcesstoken();
        try {
            JSONObject param = JSONUtil.createObj().set("code", code);
            String jsonstr = HttpUtil.post(tokenUrl, JSONUtil.toJsonStr(param));
            JSONObject jo  = JSONUtil.parseObj(jsonstr);
            // Result result = JSONUtil.toBean(jsonstr, Result.class);
            if (Integer.parseInt(jo.get("errcode").toString()) == 0) {
                JSONObject numJo = JSONUtil.parseObj(jo.get("phone_info").toString());
                String number = numJo.get("purePhoneNumber").toString();
                return number;
            } else {
                throw new BusinessException("未获取到手机号 异常：" + jo.get("errmsg") + "("+jo.get("errcode")+")");
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }


    /**
     * 获取小程序菊花码
     *parm：machineNo    二维码想携带的参数
     **/
    public static boolean getWXCode(String context, String fileName, String rootPath) {
        boolean result =  false;
        try {
            //这里调用的是上面的获取access_token方法
            String access_token = getWxAcesstoken();

            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            Map<String, String> param = new HashMap<>();
            param.put("scene", context);
            //这里的page如果没有的话可以不写，默认是跳主页，如果写了没有的页面的话，会返回错误信息
//            param.put("page", "pages/index/index");
            String json = JSONUtil.toJsonStr(param);
            ByteArrayInputStream inputStream = sendPost(url, json);
            //这里判断的是返回的图片还是错误信息，一般错误信息不会大于200
            if (inputStream.available() <= 200) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int i;
                byte[] buffer = new byte[200];
                while ((i = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, i);
                }
                String str = new String(byteArrayOutputStream.toByteArray());
                //错误信息的格式在官方文档里有
                JSONObject jsonObject = JSONUtil.parseObj(str);
                if ("41030".equals(jsonObject.get("errcode"))) {
                    throw new BusinessException("所传page页面不存在，或者小程序没有发布");
                } else if ("45009".equals(jsonObject.get("errcode"))) {
                    throw new BusinessException("调用分钟频率受限");
                }
                byteArrayOutputStream.close();
            }
            File dirFile = new File(rootPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            //输出到本地的代码
            FileOutputStream fileOutputStream = new FileOutputStream(dirFile + "/" + fileName);
            int i;
            byte[] buffer = new byte[200];
            while ((i = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, i);
            }
            fileOutputStream.flush();
            fileOutputStream.close();

            inputStream.close();
            P.green("二维码生成成功");
            result = true;
        } catch (Exception e) {
            throw new BusinessException("获取二维码异常 >>> " + e.getMessage());
        }
        return result;
    }


    public static ByteArrayInputStream sendPost(String URL, String json) {
        InputStream inputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                // 创建一个Buffer字符串
                byte[] buffer = new byte[1024];
                // 每次读取的字符串长度，如果为-1，代表全部读取完毕
                int len = 0;
                // 使用一个输入流从buffer里把数据读取出来
                while ((len = inputStream.read(buffer)) != -1) {
                    // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                    outStream.write(buffer, 0, len);
                }
                // 关闭输入流
                inputStream.close();
                // 把outStream里的数据写入内存
                byteArrayInputStream = new ByteArrayInputStream(outStream.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArrayInputStream;
    }
}
